
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "crc32.h"


#define MAX_FILE_NAME_SIZE         128

/*
* get file size
*/
int get_file_size(char *file_name)
{
	struct stat file_stat;
	
	stat(file_name, &file_stat);
	
	return file_stat.st_size;
}

/* help menu */
void print_usage(void)
{
	printf("Usage: <input file> <output file> <version>\n");
	printf("<version>: user-specified (4 characters)\n");
}

void print_image_info(mcu_head_tp p)
{
	printf("==============================================\n");
	printf("Summary ==>\n");
	printf("Image magic num       : 0x%x\n",p->magic);
	printf("Image length          : %d Byte\n",p->len);
	printf("Image version         : %d\n",p->ver);
	printf("Image crc num         : 0x%x\n",p->img_crc);
}

int main(int argc, char * const argv[] )
{
	FILE *fp_input_file = NULL;
	FILE *fp_output_file = NULL;
	char input_file_name[MAX_FILE_NAME_SIZE + 1] = {0};
	char output_file_name[MAX_FILE_NAME_SIZE + 1] = {0};
	int file_size = 0;
	char *p_buf = NULL;
	char *p = NULL;
	int read_count = 0;
	int write_count = 0;
	int total_count = 0;
	mcu_head_tp phead;
	unsigned int ver = 0;
	
	if (argc < 3)
	{
		print_usage();
		return -1;
	}
	
	if (argc > 3)
		ver = strtoul(argv[3],NULL, 10);
	
	strncpy(input_file_name, argv[1], MAX_FILE_NAME_SIZE);
	strncpy(output_file_name, argv[2], MAX_FILE_NAME_SIZE);
	printf("header size = %ld\n",sizeof(struct mcu_upgrade_head));
	
	fp_input_file = fopen(input_file_name, "rb");
	if (!fp_input_file)
	{
		printf("open %s Error!\n", input_file_name);
		return -1;
	}
	
	file_size = get_file_size(input_file_name);
	
	p_buf = (char *)malloc(file_size + sizeof(struct mcu_upgrade_head));
	memset(p_buf, 0, file_size + sizeof(struct mcu_upgrade_head));
	
	p = p_buf + sizeof(struct mcu_upgrade_head);
	phead = (mcu_head_tp)p_buf;
	
	while( (read_count = fread(p, 1,1024, fp_input_file)) != 0 )
	{
		p += read_count;
		total_count += read_count;
	}
	
	phead->magic = MCU_UPGRADE_MAGIC_NUM;
	phead->ver = ver;
	phead->len = file_size;
	phead->img_crc = crc32(p_buf + sizeof(struct mcu_upgrade_head), file_size);
	phead->header_crc = crc32(p_buf , sizeof(struct mcu_upgrade_head) - sizeof(int));
	
	print_image_info(phead);
	
	fp_output_file = fopen(output_file_name, "wb+");
	if (!fp_output_file)
	{
		printf("Open file %s Error!\n", output_file_name);
		return -1;
	}
	
	p = p_buf;
	total_count = total_count + sizeof(struct mcu_upgrade_head);
	write_count = fwrite(p,1,total_count,fp_output_file);
	printf("Output file %s size   :%d\n",output_file_name, write_count);
	
	if (write_count != total_count)
		printf("Image convert fail!!!!\n");
	
	fclose(fp_output_file);
	fclose(fp_input_file);
	free(p_buf);
	
	return 0;
}
